<?php
require_once $_SERVER['DOCUMENT_ROOT'].'/entities/Entity.php';
require_once $_SERVER['DOCUMENT_ROOT'].'/entities/Responsibility.php';
require_once $_SERVER['DOCUMENT_ROOT'].'/entities/IndicatorValue.php';
require_once $_SERVER['DOCUMENT_ROOT'].'/model/Service/Service.php';
require_once $_SERVER['DOCUMENT_ROOT'].'/model/DAO/IndicatorValueDAO.php';
require_once $_SERVER['DOCUMENT_ROOT'].'/exceptions/DataBaseException.php';
require_once $_SERVER['DOCUMENT_ROOT'].'/utils/Str.php';
// удалить, это здесь для тестирования работоспособности!!!
require_once $_SERVER['DOCUMENT_ROOT'].'/model/Service/ServiceFactory.php';

class IndicatorValueDAOImpl extends IndicatorValueDAO {

	public function create(Entity $indicatorValue) {
		/*		$sql = 'INSERT INTO `indicator_value` (`quarter`,`id_responsibility`,`plan_value`,`value`';

				$sql .= ') VALUES ("'.$indicatorValue->getQuarter().'"';
						$sql .= ','.$indicatorValue->getResponsibility()->getIdentity().'"';
							
						if($indicatorValue->getPlanValue() !== null) {
						$sql .= ','.$indicatorValue->getPlanValue();
						} else $sql .= ',NULL';

						if($indicatorValue->getValue() !== null) {
						$sql .= ','.$indicatorValue->getValue();
						} else $sql .= ',NULL';

						$sql .= ')';

		try {
		$this->query($sql);
		$indicatorValue->setIdentity($this->identity());
		return $indicatorValue;
		} catch(DataBaseException $excepton) {
		return null;
		}
		*/

		$quarter = $indicatorValue->getQuarter();
		$id_responsibility = $indicatorValue->getResponsibility()->getIdentity();
		$plan_value = $indicatorValue->getPlanValue();
		$value = $indicatorValue->getValue();

		$stmt = $this->dbh->connection->prepare('INSERT INTO `indicator_value` (`quarter`, `id_responsibility`, `plan_value`, `value`) VALUES (?, ?, ?, ?)');
		$stmt->bindValue(1, $quarter);
		$stmt->bindValue(2, $id_responsibility);
		if($plan_value !== null) {
			$stmt->bindValue(3, $plan_value);
		} else {
			$stmt->bindValue(3, NULL);
		}
		if($value !== null) {
			$stmt->bindValue(4, $value);
		} else {
			$stmt->bindValue(4, NULL);
		}

		try {
			$this->dbh->query($stmt);
			$indicatorValue->setIdentity($this->dbh->identity());
			return $indicatorValue;
		} catch (PDOException $exception) {
			return null;
		}

	}

	public function read($identity) {
		/*		$indicatorValues = $this->build('`id`='.(int)$identity);
		 if(count($indicatorValues) == 1) {
		return $indicatorValues[0];
		} else {
		return null;
		}
		*/

		$id = ((int)$identity);
		$params = array("1"=>$id);

		$indicatorValues = $this->build('`id`=?',$params);

		if(count($indicatorValues) == 1) {
			return $indicatorValues[0];
		} else {
			return null;
		}

	}

	public function update(Entity $indicatorValue) {
		/*		$sql = 'UPDATE `indicator_value` ';
		 $sql .= 'SET `quarter`='.$indicatorValue->getQuarter();
		$sql .= ',`id_responsibility`='.$indicatorValue->getResponsibility()->getIdentity();
		if($indicatorValue->getPlanValue() !== null) {
		$sql .= ',`plan_value`='.$indicatorValue->getPlanValue();
		} else {
		$sql .= ',`plan_value`=NULL';
		}
		if($indicatorValue->getValue() !== null) {
		$sql .= ',`value`='.$indicatorValue->getValue();
		} else {
		$sql .= ',`value`=NULL';
		}

		$sql .= ' WHERE `id`='.$indicatorValue->getIdentity();
		try {
		$this->query($sql);
		$indicatorValue->setIdentity($this->identity());
		return $indicatorValue;
		} catch(DataBaseException $excepton) {
		return null;
		}
		*/

		$quarter = $indicatorValue->getQuarter();
		$id_responsibility = $indicatorValue->getResponsibility()->getIdentity();
		$plan_value = $indicatorValue->getPlanValue();
		$value = $indicatorValue->getValue();
		$id = ((int)$indicatorValue->getIdentity());

		$stmt = $this->dbh->connection->prepare('UPDATE `indicator_value` SET `quarter`=?, `id_responsibility`=?, `plan_value`=?, `value`=? WHERE `id`=?');
		$stmt->bindValue(1, $quarter);
		$stmt->bindValue(2, $id_responsibility);
		if($plan_value !== null) {
			$stmt->bindValue(3, $plan_value);
		} else {
			$stmt->bindValue(3, NULL);
		}
		if($value !== null) {
			$stmt->bindValue(4, $value);
		} else {
			$stmt->bindValue(4, NULL);
		}
		$stmt->bindValue(5, $id);

		try {
			$this->dbh->query($stmt);
			//$indicatorValue->setIdentity($this->dbh->identity());
			return $indicatorValue;
		} catch (PDOException $exception) {
			return null;
		}

	}

	// создает массив экземпляров класса IndicatorValue на основе SQL-запроса на выборку с условием $condition
	private function build($condition,$params) {
		/*		$sql = 'SELECT `id`, `quarter`,`id_responsibility`,`plan_value`,`value`';
		 $sql .= 'FROM `indicator_value`';
		if($condition !== null) {
		$sql .= ' WHERE '.$condition;
		}
		$indicatorValues = array();
		$this->query($sql);
		while($row = $this->row()) {
		$indicatorValue = new IndicatorValue();
		$indicatorValue->setIdentity($row['id']);
		$indicatorValue->setQuarter($row['quarter']);
		$indicatorValue->setPlanValue($row['plan_value']);
		$indicatorValue->setValue($row['value']);
			
		$serviceResponsibility = getService('ResponsibilityService');
		$responsibility = new Responsibility();
		$responsibility = $serviceResponsibility->read($row['id_responsibility']);

		$indicatorValue->setResponsibility($responsibility);
		$indicatorValues[] = $indicatorValue;
		}
		$this->close();
		return $indicatorValues;
		*/

		$sql = 'SELECT `id`, `quarter`, `id_responsibility`, `plan_value`, `value` FROM `indicator_value`';
		if($condition !== null) {
			$sql = 'SELECT `id`, `quarter`, `id_responsibility`, `plan_value`, `value` FROM `indicator_value` WHERE ?';
			$stmt = $this->dbh->connection->prepare($sql);
			if($condition !== null) {
				foreach ($params as $i=>$value){
					$stmt->bindValue($i, $value);
				}
					
			}
			$this->dbh->query($sql);
		}else{
			$this->dbh->execute($sql);
		}
		$indicatorValues = array();
		while($row = $this->dbh->row()) {
			$indicatorValue = new IndicatorValue();
			$indicatorValue->setIdentity($row['id']);
			$indicatorValue->setQuarter($row['quarter']);
			$indicatorValue->setPlanValue($row['plan_value']);
			$indicatorValue->setValue($row['value']);

			// удалить потом это!!!
			// 			$serviceFactoy = new ServiceFactory(); // Создаем фабрику сервисов
			// 			$serviceResponsibility = $serviceFactoy->getService('ResponsibilityService');// Получаем нужный сервис
			// это раскомментить, это исходное!!!
			//$serviceResponsibility = getService('ResponsibilityService');
			$responsibility = new Responsibility();
			$responsibility->setIdentity($row['id_responsibility']);
			//= $serviceResponsibility->read($row['id_responsibility']);
			$indicatorValue->setResponsibility($responsibility);
			$indicatorValues[] = $indicatorValue;
		}
		$this->dbh->close();
		return $indicatorValues;
	}

	//возвращает indicatorValue ооответвующие данной Обязанности
	public function getByResponsibility($identity) {
		/*		return $this->build('`id_responsibility`='.(int)$identity);*/

		$id = ((int)$identity);
		$params = array("1"=>$id);
		return $this->build('`id_responsibility`=?',$params);

	}

	public function delete($identity){
		$id = ((int)$identity);

		$stmt = $this->dbh->connection->prepare('DELETE FROM `indicator_value` WHERE `id`=?');
		$stmt->bindValue(1, $id);

		try {
			$this->dbh->query($stmt);
			return true;
		} catch (PDOException $exception) {
			return false;
		}

	}


}

?>